import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_scaffold/flutter_scaffold.dart';

@Deprecated('Use ViewModelWidgetState instead this')
class BindViewModel<T extends BaseViewModel> extends StatefulWidget {
  final GetControllerBuilder<T> builder;

  final T init;

  final bool permanent;

  final String? tag;

  const BindViewModel({super.key, required this.init, required this.builder, this.permanent = false, this.tag});

  @override
  State<BindViewModel> createState() => _ViewModelWidgetState<T>();
}

/// 假如有3个页面，分别是A、B、C，跳转逻辑由A->B->C，而RouteAware使用with混淆在B中。
/// didPopNext：在C页面关闭后，B页面调起该方法；
/// didPush: 当由A打开B页面时，B页面调起该方法；
/// didPop: 当B页面关闭时，B页面调起该方法；
/// didPushNext: 当从B页面打开C页面时，该方法被调起。
/// @author zhibo.huang
/// @date   2025/6/16
class _ViewModelWidgetState<T extends BaseViewModel> extends State<BindViewModel<T>> with RouteAware {
  final RouteObserver<Route> routeObserver = RouteObserverUtil().routeObserver;

  @override
  void initState() {
    Get.put(widget.init, tag: widget.tag, permanent: widget.permanent);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<T>(builder: widget.builder, tag: widget.tag, autoRemove: widget.permanent);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route != null) {
      routeObserver.subscribe(this, route);
    }
  }

  @override
  void didUpdateWidget(covariant BindViewModel<T> oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didPopNext() {
    super.didPopNext();
    Get.find<T>(tag: widget.tag).onResumed();
  }

  @override
  void didPushNext() {
    super.didPushNext();
    Get.find<T>(tag: widget.tag).onPaused();
  }

  @override
  void dispose() {
    super.dispose();
    routeObserver.unsubscribe(this);
    Get.delete<T>(tag: widget.tag, force: false);
  }
}
